package org.example.common.utils;

/**
 * @Description OSSUtil
 * @Author xiaotian
 * @Date 2025-04-04
 */

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

public class OSSUtil {

    // 阿里云 OSS 配置信息
    private static final String ENDPOINT = "oss-cn-hangzhou.aliyuncs.com"; // 如 "oss-cn-hangzhou.aliyuncs.com"
    private static final String ACCESS_KEY_ID = "LTAI5tEVEhkgGwy7SJKGHNjh";
    private static final String ACCESS_KEY_SECRET = "kbaVOOCXIyhJoYlcqPNNrXBu4hF9cJ";
    private static final String BUCKET_NAME = "web1-tlias-1";

    /**
     * 上传文件到阿里云 OSS
     *
     * @param file 文件对象
     * @return 文件的访问 URL
     */
    public static String uploadFile(MultipartFile file) {
        // 创建 OSS 客户端
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 生成唯一的文件名
            String fileName = generateFileName(file.getOriginalFilename());

            // 上传文件到指定路径
            ossClient.putObject(BUCKET_NAME, "avatars/" + fileName, inputStream);

            // 返回文件的访问 URL
            return "https://" + BUCKET_NAME + "." + ENDPOINT + "/avatars/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        } finally {
            // 关闭 OSS 客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 生成唯一的文件名
     *
     * @param originalFilename 原始文件名
     * @return 唯一文件名
     */
    private static String generateFileName(String originalFilename) {
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        return UUID.randomUUID().toString() + extension;
    }
}